﻿using System;
using System.Runtime.InteropServices;
using System.Text;
using Core;

namespace App
{
	public static class CQEvent
	{
		private static readonly Encoding gb18030 = Encoding.GetEncoding("gb18030");

		[DllExport("AppInfo", CallingConvention = CallingConvention.StdCall)]
		public static string AppInfo()
		{
			string ApiVer = "9";                //Api版本号
			string AppID = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;  //使用当前程序集名称
			return string.Concat(ApiVer, ",", AppID);
		}

		[DllExport("Initialize", CallingConvention = CallingConvention.StdCall)]
		public static int Initialize(int AuthCode)
		{
			return Main.Initialize(AuthCode);
		}

		//Type=1001 酷Q启动
		[DllExport("_eventStartup", CallingConvention = CallingConvention.StdCall)]
		public static int AppStartup()
		{
			return Main.AppStartup();
		}

		//Type=1002 酷Q退出
		[DllExport("_eventExit", CallingConvention = CallingConvention.StdCall)]
		public static int AppExit()
		{
			return Main.AppExit();
		}

		//Type=1003 应用已被启用
		[DllExport("_eventEnable", CallingConvention = CallingConvention.StdCall)]
		public static int AppEnable()
		{
			return Main.AppEnable();
		}

		//Type=1004 应用将被停用
		[DllExport("_eventDisable", CallingConvention = CallingConvention.StdCall)]
		public static int AppDisable()
		{
			return Main.AppDisable();
		}

		//Type=21 私聊消息
		[DllExport("_eventPrivateMsg", CallingConvention = CallingConvention.StdCall)]
		public static int PrivateMessage(int subType, int msgId, long fromQQ, IntPtr msg, int font)
		{
			return Main.PrivateMessage(subType, msgId, fromQQ, EventHelp.GetStrA(msg, gb18030), font);
		}

		//Type=2 群消息
		[DllExport("_eventGroupMsg", CallingConvention = CallingConvention.StdCall)]
		public static int GroupMessage(int subType, int msgId, long fromGroup, long fromQQ, IntPtr fromAnonymous, IntPtr msg, int font)
		{
			return Main.GroupMessage(subType, msgId, fromGroup, fromQQ, EventHelp.GetStrA(fromAnonymous, gb18030), EventHelp.GetStrA(msg, gb18030), font);
		}

		[DllExport("_menuA", CallingConvention = CallingConvention.StdCall)]
		public static int _menuA()
		{
			return Main._menuA();
		}

		[DllExport("_menuB", CallingConvention = CallingConvention.StdCall)]
		public static int _menuB()
		{
			return Main._menuB();
		}
	}

	public static class EventHelp
	{
		/// <summary>
		/// 将字符串指针转为字符串变量
		/// </summary>
		/// <param name="lpString"></param>
		/// <param name="encoding">gb18030</param>
		/// <returns></returns>
		public static string GetStrA(IntPtr lpString, Encoding encoding)
		{
			int i = LstrlenA(lpString);
			if (i == 0)
			{
				return "";
			}
			byte[] by = new byte[i];
			Marshal.Copy(lpString, by, 0, i);
			return encoding.GetString(by);
		}

		[DllImport("kernel32.dll", EntryPoint = "lstrlenA", CharSet = CharSet.Ansi)]
		private static extern int LstrlenA(IntPtr lpString);
	}
}
